package com.example.demo.test;

public class ProductAndConcumer {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        new Thread(new Product(clerk), "生产者A").start();
        new Thread(new Product(clerk), "生产者B").start();
        new Thread(new Consumer(clerk), "消费者A").start();
        new Thread(new Consumer(clerk), "消费者B").start();

    }
}

class Clerk {
    private int product = 0;

    public synchronized void product() {
        while (product >= 1) {
            System.out.println("满货");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ":" + ++product);
        notifyAll();
    }

    public synchronized void sale() {
        while (product <= 0) {
            System.out.println("缺货");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ":" + --product);
        notifyAll();

    }
}

class Product implements Runnable {
    Clerk clerk;

    public Product(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.product();
        }
    }
}

class Consumer implements Runnable {
    Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.sale();
        }
    }
}
